// 引入请求api
import { reqCodeByPhone, userRegister, userLogin, reqUserInfo, reqLogOut } from '@/api/index'
import { setToken, getToken, clearToken } from '@/utils/token/index'

// 登录与注册的仓库
const state = {
    code: '',
    token: getToken('TOKEN'),
    userInfo: {}
};
const mutations = {
    GETCODE(state, code) {
        state.code = code
    },
    USERLOGIN(state, token) {
        state.token = token;
    },
    GETUSERINFO(state, userInfo) {
        state.userInfo = userInfo;
    },
    USERLOGOUT(state) {
        state.userInfo = {};
        clearToken();
        state.token = '';
    }
};
const actions = {
    // 获取验证码这个接口:把验证码返回到前台
    // 但是正常情况验证码应该发到用户的手机
    async getCode({ commit }, phoneNumber) {
        let res = await reqCodeByPhone(phoneNumber);
        if (res.code == 200) {
            commit('GETCODE', res.data);
            console.log('验证码获取成功');
            return '请求成功';
        } else {
            console.log('验证码请求失败');
            return Promise.reject(new Error('验证码请求错误'));
        }
    },

    // 用户注册
    async UserRegister({ commit }, data) {
        let res = await userRegister(data);
        if (res.code == 200) {
            console.log('注册成功');
            return '注册成功';
        } else {
            console.log('注册失败,' + res.message);
            return Promise.reject(new Error(res.message));
        }
    },

    // 用户登录
    async userLogin({ commit }, data) {
        let res = await userLogin(data);
        if (res.code == 200) {
            // 存储服务器下发的token
            // 将来经常带token向服务器请求用户信息
            commit('USERLOGIN', res.data.token);
            // 用户已经登录成功而且已经获取到了token
            // 持久化存储token
            setToken(res.data.token);
            console.log('登录成功');
            return '登录成功!';
        } else {
            console.log('账号或密码错误');
            return Promise.reject(new Error('账号或密码错误'));
        }
    },

    // 获取用户信息
    async getUserInfo({ commit }) {
        let res = await reqUserInfo();
        if (res.code == 200) {
            commit('GETUSERINFO', res.data);
            console.log('请求用户信息成功');
            return '请求用户信息成功';
        } else {
            console.log('请求用户信息失败');
            return Promise.reject(new Error(res.message));
        }
    },

    // 用户退出
    async UerLogOut({ commit }) {
        let res = await reqLogOut();
        if (res.code == 200) {
            commit('USERLOGOUT');
            console.log('退出成功');
            return '退出成功';
        } else {
            console.log('退出失败');
            return Promise.reject(new Error(res.message));
        }
    }
};
const getters = {};
export default {
    state,
    mutations,
    actions,
    getters
}